package apifm

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	utilx "mall/common/utils/user"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserDetailLogic {
	return &GetUserDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserDetailLogic) GetUserDetail(
	req *types.GetUserProfileReq,
	headers *[]*types.Header,
) (*types.MockMePageResp, error) {
	userId := jwt.GetUserId(l.ctx)
	if userId > 0 {
		var platform string
		if req.AuthType == nil || len(strings.TrimSpace(*req.AuthType)) == 0 {
			platform = globalkey.UserAuthTypeWechatMini
		} else {
			platform = *req.AuthType
		}
		platformId := utilx.GetThirdPartyPlatformId(platform)
		if platformId == 0 {
			return nil, resultx.NewErrCode(resultx.USER_AUTH_PARAM_INVALID)
		}

		res, err := l.svcCtx.UserRpc.GetCurrentUser(l.ctx, &userclient.GetUserReq{
			PlatformId:      pointy.GetPointer(platformId),
			UserId:          pointy.GetPointer(userId),
			WithAuthInfo:    pointy.GetPointer(uint32(1)),
			WithDetailInfo:  pointy.GetPointer(uint32(1)),
			WithAccountInfo: pointy.GetPointer(uint32(1)),
		})
		if err != nil {
			logx.Errorw("GetUserDetail GetCurrentUser err", logx.Field("detail", err.Error()))
			//
			return nil, resultx.NewErrCode(resultx.USER_GET_INFO_FAILED)
		}

		var userId *string
		var status uint32
		var role uint32
		var nickname *string
		var avatar *string
		var likeEntryCount *uint32
		var collectEntryCount *uint32
		var rankId uint64
		var frozenPoint *uint64
		var availablePoint *uint64
		if res.User != nil {
			userId = res.User.Id
			if res.User.Status != nil {
				status = *res.User.Status
			}
		}
		if res.UserDetail != nil {
			if res.UserDetail.Role != nil {
				role = *res.UserDetail.Role
			}
			likeEntryCount = res.UserDetail.LikeEntryCount
			collectEntryCount = res.UserDetail.CollectEntryCount
		}
		if res.UserAccount != nil {
			if res.UserAccount.RankId != nil {
				rankId = *res.UserAccount.RankId
			}
			frozenPoint = res.UserAccount.FrozenPoint
			availablePoint = res.UserAccount.AvailablePoint
		}
		if res.UserAuth != nil {
			nickname = res.UserAuth.Nickname
			avatar = res.UserAuth.Avatar
		}

		if userId != nil && len(*userId) > 0 {
			now := time.Now().Unix()
			accessExpire := l.svcCtx.Config.Auth.AccessExpire
			var securityStatus string
			switch int32(status) {
			case globalkey.StatusDisabled:
				securityStatus = jwt.SUSPENDED
			case globalkey.StatusExpired:
				securityStatus = jwt.CANCELLED
			case globalkey.StatusDeleted:
				securityStatus = jwt.BANNED
			case globalkey.StatusAsGuest:
				securityStatus = jwt.ANONYMOUS
			default:
				securityStatus = jwt.CERTIFICATED
			}
			token, err := jwt.NewJwtToken(
				l.svcCtx.Config.Auth.AccessSecret,
				now,
				accessExpire,
				jwt.WithOption("userId", *userId),
				jwt.WithOption("rankId", rankId),
				jwt.WithOption("role", role),
				jwt.WithOption("securityStatus", securityStatus),
			)
			if err != nil {
				logx.Errorw("GetUserDetail NewJwtToken err", logx.Field("detail", err.Error()))
				return nil, resultx.NewErrCode(resultx.USER_GET_INFO_FAILED)
			}

			*headers = []*types.Header{
				{
					Key:   "authorization",
					Value: token,
				},
			}
		}

		return &types.MockMePageResp{
			UserInfo: &types.UserInfo{
				Id:       userId,
				Nickname: nickname,
				Avatar:   avatar,
			},
			UserDetail: &types.UserDetail{
				LikeEntryCount:    likeEntryCount,
				CollectEntryCount: collectEntryCount,
				FrozenPoint:       frozenPoint,
				AvailablePoint:    availablePoint,
			},
		}, nil
	}

	return &types.MockMePageResp{}, nil
}
